﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using MotionCS.Helper;

namespace MotionCS.Serial
{
    public class SerialBasic
    {
        /// <summary>
        /// 串口
        /// </summary>
        private SerialPort serial;
        /// <summary>
        /// 数据接收事件
        /// </summary>
        public event Action<string> DataReceive;
        /// <summary>
        /// 是否打开
        /// </summary>
        public bool IsOpen { get => serial.IsOpen; }
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public SerialBasic()
        {
            serial = new SerialPort();
        }
        /// <summary>
        /// 串口打开
        /// </summary>
        /// <param name="name"></param>
        /// <param name="rate"></param>
        public void Open(string name, Int32 rate, int parity = (int)Parity.None, int databits = 8, int stopbits = (int)StopBits.One)
        {
            try
            {
                serial.PortName = name;
                serial.BaudRate = rate;
                serial.Parity = (Parity)parity;
                serial.DataBits = databits;
                serial.StopBits = (StopBits)stopbits;
                serial.Encoding = Encoding.UTF8;
                serial.DataReceived += new SerialDataReceivedEventHandler(ReceiveData);

                serial.Open();
                Logger.Logout(name + "打开成功.");
            }
            catch (Exception ex)
            {
                Logger.Logout(name + "打开失败.");
                Logger.Logerr(ex.Message.ToString());
            }
        }
        /// <summary>
        /// 串口关闭
        /// </summary>
        public void Close()
        {
            try
            {
                serial.Close();
            }
            catch
            {
                Logger.Logout(serial.PortName + "关闭失败.");
            }
        }
        /// <summary>
        /// 串口数据接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReceiveData(object sender, SerialDataReceivedEventArgs e)
        {
            string receiveData = serial.ReadExisting();
            DataReceive?.Invoke(receiveData);
        }
        /// <summary>
        /// 串口数据发送
        /// </summary>
        /// <param name="dataStr"></param>
        /// <returns></returns>
        public void SendData(string dataStr)
        {
            if (serial.IsOpen)
            {
                serial.Write(dataStr);
            }
            else
            {
                Logger.Logout("数据发送失败,串口未打开.");
            }
        }
    }
}
